/**
 * @file popup.js
 * @description 插件弹出窗口的主要交互逻辑
 */

import showdown from 'showdown';
import { giteeService } from './services/gitee';

// DOM元素
const renderModeBtn = document.getElementById('renderMode');
const sourceModeBtn = document.getElementById('sourceMode');
const downloadBtn = document.getElementById('downloadBtn');
const copyBtn = document.getElementById('copyBtn');
const tocPanel = document.getElementById('tocPanel');
const toggleTocBtn = document.getElementById('toggleToc');
const tocContent = document.getElementById('tocContent');
const markdownContent = document.getElementById('markdownContent');
const sourceEditor = document.getElementById('sourceEditor');
const renderContent = document.getElementById('renderContent');
const shareBtn = document.getElementById('shareBtn');
const giteeConfigDialog = document.getElementById('giteeConfigDialog');
const directoryDialog = document.getElementById('directoryDialog');
const directoryList = document.getElementById('directoryList');
const newDirectory = document.getElementById('newDirectory');
const createDirectory = document.getElementById('createDirectory');
const confirmDirectory = document.getElementById('confirmDirectory');
const cancelDirectory = document.getElementById('cancelDirectory');
const saveGiteeConfig = document.getElementById('saveGiteeConfig');
const cancelGiteeConfig = document.getElementById('cancelGiteeConfig');
const giteeToken = document.getElementById('giteeToken');
const giteeOwner = document.getElementById('giteeOwner');
const giteeRepo = document.getElementById('giteeRepo');

// 状态变量
let currentMode = 'render'; // 'render' 或 'source'
let markdownText = ''; // 存储Markdown文本
let pageTitle = ''; // 存储页面标题
let selectedDirectory = '';
let lastUsedDirectory = '';

/**
 * 初始化popup页面
 */
async function initPopup() {
    try {
        // 获取当前标签页信息
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (!tab) {
            throw new Error('No active tab found');
        }

        console.log('当前标签页信息:', {
            tabId: tab.id,
            tabTitle: tab.title,
            tabUrl: tab.url
        });

        // 确保content script已经注入
        await ensureContentScriptInjected(tab);
        
        // 向content script发送消息，获取页面内容
        const response = await chrome.tabs.sendMessage(tab.id, { action: 'getPageContent' });
        
        if (response && response.success) {
            console.log('页面内容解析结果:', {
                tabTitle: tab.title,
                originalPageTitle: response.pageTitle
            });

            markdownText = response.markdown;
            
            // 标题优先级选择：标签页标题 > 原始页面标题 > 默认标题
            const titleSource = tab.title ? '标签页标题' :
                              response.pageTitle ? '原始页面标题' : 
                              '默认标题';
            
            pageTitle = tab.title || response.pageTitle || '未命名文档';
            
            console.log('最终选择的标题:', {
                selectedTitle: pageTitle,
                source: titleSource
            });
            
            // 更新显示
            updateDisplay();
            // 生成目录
            generateToc();
        } else {
            console.warn('获取页面内容失败:', response);
        }
    } catch (error) {
        console.error('初始化失败:', error);
        markdownContent.innerHTML = '<p class="ps-error">获取页面内容失败，请刷新页面重试。</p>';
    }
}

/**
 * 确保content script已经注入
 * @param {chrome.tabs.Tab} tab 当前标签页
 */
async function ensureContentScriptInjected(tab) {
    try {
        // 尝试发送测试消息
        await chrome.tabs.sendMessage(tab.id, { action: 'ping' });
    } catch (error) {
        // 如果消息发送失败，说明content script还没有注入，手动注入
        await chrome.scripting.executeScript({
            target: { tabId: tab.id },
            files: ['vendor.bundle.js', 'content.bundle.js']
        });
    }
}

/**
 * 更新显示内容
 */
function updateDisplay() {
    if (currentMode === 'render') {
        // 隐藏源码编辑器，显示渲染内容
        sourceEditor.style.display = 'none';
        renderContent.style.display = 'block';
        
        // 使用showdown转换Markdown为HTML
        const converter = new showdown.Converter({
            tables: true,
            tasklists: true,
            strikethrough: true,
            emoji: true
        });
        const html = converter.makeHtml(markdownText);
        renderContent.innerHTML = html;
        
        // 更新目录
        generateToc();
    } else {
        // 显示源码编辑器，隐藏渲染内容
        sourceEditor.style.display = 'block';
        renderContent.style.display = 'none';
        
        // 更新编辑器内容
        sourceEditor.value = markdownText;
    }
}

/**
 * 生成目录
 */
function generateToc() {
    const headings = markdownText.match(/^#{1,6}.+$/gm) || [];
    const toc = headings.map(heading => {
        const level = heading.match(/^#+/)[0].length;
        const text = heading.replace(/^#+\s*/, '');
        return `<div class="ps-toc-item" style="padding-left: ${(level - 1) * 16}px">
            <a href="#${text.toLowerCase().replace(/\s+/g, '-')}">${text}</a>
        </div>`;
    }).join('');
    
    tocContent.innerHTML = toc;
}

/**
 * HTML转义
 * @param {string} text 需要转义的文本
 * @returns {string} 转义后的文本
 */
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

/**
 * 处理文件名，移除/替换非法字符
 * @param {string} title 原始标题
 * @returns {string} 处理后的合法文件名
 */
function sanitizeFilename(title) {
    if (!title || typeof title !== 'string') {
        return '未命名文档';
    }

    // 移除或替换Windows和Unix系统中的非法字符
    const illegalChars = /[<>:"/\\|?*\x00-\x1F]/g;
    // 替换连续的空格、点、破折号和下划线
    const multipleSpaces = /\s+/g;
    const multipleDots = /\.+/g;
    const multipleDashes = /-+/g;
    const multipleUnderscores = /_+/g;
    
    return title
        .trim() // 移除首尾空格
        .replace(illegalChars, '-') // 将非法字符替换为破折号
        .replace(multipleSpaces, ' ') // 多个空格替换为单个空格
        .replace(multipleDots, '.') // 多个点替换为单个点
        .replace(multipleDashes, '-') // 多个破折号替换为单个破折号
        .replace(multipleUnderscores, '_') // 多个下划线替换为单个下划线
        .replace(/^[.-]+|[.-]+$/g, '') // 移除首尾的点号和破折号
        .substring(0, 200) // 限制文件名长度为200字符
        || '未命名文档'; // 如果处理后为空字符串，则使用默认名称
}

/**
 * 下载Markdown文件
 */
async function downloadMarkdown() {
    try {
        const filename = `${sanitizeFilename(pageTitle)}.md`;
        const blob = new Blob([markdownText], { type: 'text/markdown' });
        
        const downloadId = await chrome.downloads.download({
            url: URL.createObjectURL(blob),
            filename: filename,
            saveAs: true
        });

        // 添加下载成功的视觉反馈
        downloadBtn.classList.add('ps-success');
        setTimeout(() => downloadBtn.classList.remove('ps-success'), 2000);
    } catch (error) {
        console.error('下载失败:', error);
        markdownContent.innerHTML = '<p class="ps-error">下载失败，请重试。</p>';
    }
}

/**
 * 复制Markdown内容到剪贴板
 */
async function copyToClipboard() {
    try {
        await navigator.clipboard.writeText(markdownText);
        // 显示复制成功提示
        copyBtn.classList.add('ps-success');
        setTimeout(() => copyBtn.classList.remove('ps-success'), 2000);
    } catch (error) {
        console.error('复制失败:', error);
    }
}

// 监听源码编辑器的输入事件
sourceEditor.addEventListener('input', () => {
    // 更新markdown文本
    markdownText = sourceEditor.value;
});

// Gitee相关功能
/**
 * 显示Gitee配置对话框
 */
function showGiteeConfig() {
    giteeConfigDialog.style.display = 'flex';
    loadGiteeConfig();
}

/**
 * 隐藏Gitee配置对话框
 */
function hideGiteeConfig() {
    giteeConfigDialog.style.display = 'none';
}

/**
 * 加载Gitee配置
 */
async function loadGiteeConfig() {
    try {
        const config = await giteeService.getConfig();
        if (config) {
            giteeToken.value = config.token || '';
            giteeOwner.value = config.owner || '';
            giteeRepo.value = config.repo || '';
        }
    } catch (error) {
        console.error('加载配置失败:', error);
    }
}

/**
 * 保存Gitee配置
 */
async function handleSaveGiteeConfig() {
    const config = {
        token: giteeToken.value.trim(),
        owner: giteeOwner.value.trim(),
        repo: giteeRepo.value.trim()
    };

    if (!config.token || !config.owner || !config.repo) {
        alert('请填写完整的配置信息');
        return;
    }

    try {
        await giteeService.saveConfig(config);
        giteeService.init(config);
        hideGiteeConfig();
        alert('配置保存成功');
    } catch (error) {
        console.error('保存配置失败:', error);
        alert('配置保存失败，请重试');
    }
}

/**
 * 显示目录选择对话框
 */
async function showDirectoryDialog() {
    try {
        const config = await giteeService.getConfig();
        if (!config) {
            showGiteeConfig();
            return;
        }

        giteeService.init(config);
        directoryDialog.style.display = 'flex';
        loadDirectories();
    } catch (error) {
        console.error('显示目录对话框失败:', error);
        alert('获取目录失败，请检查配置');
    }
}

/**
 * 隐藏目录选择对话框
 */
function hideDirectoryDialog() {
    directoryDialog.style.display = 'none';
    selectedDirectory = '';
}

/**
 * 加载目录列表
 */
async function loadDirectories() {
    try {
        const directories = await giteeService.getDirectories();
        directoryList.innerHTML = directories.map(dir => `
            <div class="ps-directory-item ${dir.path === lastUsedDirectory ? 'selected' : ''}" 
                 data-path="${dir.path}">
                <svg class="ps-directory-icon" viewBox="0 0 24 24">
                    <path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/>
                </svg>
                ${dir.name}
            </div>
        `).join('');

        // 添加目录点击事件
        document.querySelectorAll('.ps-directory-item').forEach(item => {
            item.addEventListener('click', () => {
                document.querySelectorAll('.ps-directory-item').forEach(i => i.classList.remove('selected'));
                item.classList.add('selected');
                selectedDirectory = item.dataset.path;
            });
        });
    } catch (error) {
        console.error('加载目录失败:', error);
        directoryList.innerHTML = '<div class="ps-error">加载目录失败，请重试</div>';
    }
}

/**
 * 创建新目录
 */
async function createNewDirectory() {
    const dirName = newDirectory.value.trim();
    if (!dirName) {
        alert('请输入目录名称');
        return;
    }

    try {
        await giteeService.createDirectory(dirName);
        newDirectory.value = '';
        loadDirectories();
        alert('目录创建成功');
    } catch (error) {
        console.error('创建目录失败:', error);
        alert('创建目录失败，请重试');
    }
}

/**
 * 分享到Gitee
 */
async function shareToGitee() {
    if (!selectedDirectory) {
        alert('请选择保存目录');
        return;
    }

    try {
        const filename = `${sanitizeFilename(pageTitle)}.md`;
        const path = `${selectedDirectory}/${filename}`;

        await giteeService.uploadFile({
            path,
            content: markdownText,
            message: `docs: add ${filename}`
        });

        lastUsedDirectory = selectedDirectory;
        hideDirectoryDialog();
        alert('文件保存成功');
    } catch (error) {
        console.error('保存文件失败:', error);
        alert('保存文件失败，请重试');
    }
}

// 事件监听
renderModeBtn.addEventListener('click', () => {
    currentMode = 'render';
    renderModeBtn.classList.add('ps-active');
    sourceModeBtn.classList.remove('ps-active');
    updateDisplay();
});

sourceModeBtn.addEventListener('click', () => {
    currentMode = 'source';
    sourceModeBtn.classList.add('ps-active');
    renderModeBtn.classList.remove('ps-active');
    updateDisplay();
});

toggleTocBtn.addEventListener('click', () => {
    tocPanel.classList.toggle('ps-collapsed');
});

downloadBtn.addEventListener('click', downloadMarkdown);
copyBtn.addEventListener('click', copyToClipboard);
shareBtn.addEventListener('click', showDirectoryDialog);
saveGiteeConfig.addEventListener('click', handleSaveGiteeConfig);
cancelGiteeConfig.addEventListener('click', hideGiteeConfig);
createDirectory.addEventListener('click', createNewDirectory);
confirmDirectory.addEventListener('click', shareToGitee);
cancelDirectory.addEventListener('click', hideDirectoryDialog);

// 初始化
document.addEventListener('DOMContentLoaded', initPopup); 